import vosk
import sys
import sounddevice as sd
import queue
import json
import time
import config

model = vosk.Model(r"model_big")


samplerate = 16000
device = 1

q = queue.Queue()


def q_callback(indata, frames, time, status):
    if status:
        print(status, file=sys.stderr)
    q.put(bytes(indata))


def va_listen(callback, main_window):
    with sd.RawInputStream(samplerate=samplerate, blocksize=8000, device=device, dtype='int16',
                           channels=1, callback=q_callback):
        rec = vosk.KaldiRecognizer(model, samplerate)

        last_activation = time.time()
        activation_timer = 0
        activation_threshold = 3

        while True:
            data = q.get()
            if rec.AcceptWaveform(data):
                callback(json.loads(rec.Result())["text"], main_window)
                """ 
                result = json.loads(rec.Result())["text"]

                if result.startswith(config.VA_NAME):
                    last_activation = time.time()
                    activation_timer = 0
                    callback(result, main_window)

                elif time.time() - last_activation < activation_threshold:
                    callback(result, main_window)
                    last_activation = time.time()


                elif time.time() - last_activation > activation_threshold:
                    activation_timer = time.time() - last_activation
                    if activation_timer > activation_threshold:
                        print("Silence detected for {} seconds".format(activation_timer))
                        last_activation = time.time()


            if activation_timer > 0:
                activation_timer += time.time() - last_activation
                 """


